/**
 * Copyright (c) 2025 myons Inc. All rights reserved.
 */
package cn.zmwh.common.security.controller;

import cn.zmwh.common.core.api.BaseErrorCode;
import cn.zmwh.common.core.api.Result;
import cn.zmwh.common.core.constants.Constants;
import cn.zmwh.common.security.base.LoginService;
import cn.zmwh.common.security.base.UserService;
import cn.zmwh.common.security.config.JwtTokenUtil;
import cn.zmwh.common.security.pojo.request.LoginRequest;
import cn.zmwh.common.security.pojo.vo.LoginVo;
import cn.zmwh.common.security.service.factory.LoginServiceFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @describe: 登录 、
 * @author: dmzmwh 、
 * @time: 2025-04-04 15:43 、
 */
@Api(tags = "登录")
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginServiceFactory factory;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @PostMapping
    @ApiOperation(value = "登录 状态4001，可以直接取token")
    public Result<LoginVo> login(@RequestBody LoginRequest request) throws Exception {
        String loginType = request.getLoginType();
        LoginService loginService = factory.loginService(loginType);
        LoginVo loginVo = loginService.login(request);
        int success = loginVo.getSuccess();
        userService.loginLog(request, loginVo);
        if (success != 0) {
            return Result.ok(BaseErrorCode.NEW_TOKEN, loginVo);
        } else {
            //登录失败事件
            return Result.failed(loginVo.getMsg());
        }
    }

    @GetMapping("/refresh")
    @ApiOperation(value = "刷新token")
    public Result<LoginVo> refresh(@RequestHeader(Constants.TOKEN_HEADER) String token,
                                   @RequestHeader(Constants.UID) Long uid) {
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(jwtTokenUtil.refreshHeadToken(token));
        return Result.ok(BaseErrorCode.NEW_TOKEN, loginVo);
    }
}
